package me.jzn.alib.custom.uri;

import android.content.Context;
import android.net.Uri;

import androidx.annotation.NonNull;

import me.jzn.alib.ALib;

/**
 * 因为资源名字可能被混淆，尽量不要使用这个
 * res://raw/path-raw
 */
@Deprecated
public class ResUri implements BaseCustomUri {
    private String mType;
    private int mRes;
    private String mResName;
    private Uri mUri;

    public ResUri(String type, int res) {
        mType = type;
        mRes = res;
    }

    public ResUri(String type, String resRawName) {
        Context ctx = ALib.app();
        mType = type;
        mRes = ctx.getResources().getIdentifier(resRawName, type, ctx.getPackageName());
        mResName = resRawName;

        mUri = new Uri.Builder().scheme(BaseCustomUri.SCHEME_RES).authority(type).path(resRawName).build();
    }

    //res://raw/path-raw
    //file:///android_res/raw/
    public ResUri(Uri uri) {
        mUri = uri;
        String scheme = uri.getScheme();
        if (BaseCustomUri.SCHEME_RES.equals(scheme)) {
            String auth = uri.getAuthority();
            String path = uri.getPath();

            mType = auth;
            mResName = path;
        } else if ("file".equals(scheme)) {
            String path = uri.getPath();
            int rawEndIdx = path.indexOf("/", 1);
            String resType = path.substring(1, rawEndIdx);
            int resNameStx = path.indexOf("/", rawEndIdx + 1) + 1;
            String resName = path.substring(resNameStx);

            mType = resType;
            mResName = resName;
        }
    }

    public void setupRes(int res) {
        if (res < 1) {
            Context ctx = ALib.app();
            mRes = ctx.getResources().getIdentifier(mResName, mType, ctx.getPackageName());
        } else {
            mRes = res;
        }
    }

    public String getType() {
        return mType;
    }

    public int getRes() {
        return mRes;
    }

    public String getResName() {
        return mResName;
    }

    @Deprecated
    @NonNull
    @Override
    public String toString() {
        if (mUri == null) {
            throw new IllegalStateException("uri为空，请使用getType/getRes");
        }
        return mUri.toString();
    }

    @Override
    public String getScheme() {
        return mUri.getScheme();
    }
}
